package algorithm.niuke;

public class 二维数组中的查找 {
    public static void main(String[] args) {
        int[][] array = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
        System.out.println(Find(7, array));
    }

    public static boolean Find(int target, int[][] array) {
        try {
            int[][] direct = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { 1, 0 } };
            int[][] move = { { 0, -1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
            return scan(target, array, direct, move, 0, array.length, array[0].length, 0, 0);
        } catch (Throwable e) {
            return false;
        }
    }

    public static boolean scan(int target, int[][] array, int[][] direct, int[][] move, int time, int rowLen,
            int colLen, int row, int col) {
        if (col == colLen - 1 && row == rowLen - 1) {
            return false;
        }
        boolean findBigger = true;
        if (time == 2) {
            findBigger = false;
        }
        while (col < colLen && row < rowLen) {
            if (array[row][col] == target) {
                return true;
            }
            if ((findBigger ^ (array[row][col] > target)) == false) {
                row += move[time][0];
                col += move[time][1];
                break;
            }
            row += direct[time][0];
            col += direct[time][1];
        }
        if (col == colLen) {
            col--;
        }
        if (col == -1) {
            col++;
        }
        if (row == rowLen) {
            row--;
        }
        if (row == -1) {
            row++;
        }
        return scan(target, array, direct, move, (time + 1) % 4, rowLen, colLen, row, col);
    }
}
